import cloud.tianai.nio.channel.Channel;
import cloud.tianai.nio.channel.NioSocketChannel;
import cloud.tianai.nio.handler.ChannelHandlerContext;
import cloud.tianai.nio.handler.ChannelInboundHandler;
import cloud.tianai.nio.handler.ChannelOutboundHandler;
import cloud.tianai.nio.loop.NioEventLoopGroup;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class ClientDemo {

    public static void main(String[] args) throws IOException, InterruptedException {
        NioEventLoopGroup eventLoops = new NioEventLoopGroup(1);
        NioSocketChannel nioSocketChannel = new NioSocketChannel();
        eventLoops.register(nioSocketChannel);
        nioSocketChannel.getPipeline()
                .addLast((ChannelInboundHandler) (ctx, msg) -> {
                    ByteBuffer buffer = (ByteBuffer) msg;
                    CharBuffer decode = StandardCharsets.UTF_8.decode(buffer);
                    String s = decode.toString();
                    System.out.println("回传数据:" + s);

                })
                .addLast((ChannelOutboundHandler) (ctx,msg) -> {
                    ctx.write(StandardCharsets.UTF_8.encode((String) msg));
                });
        nioSocketChannel.connect(new InetSocketAddress(9999));

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String str = scanner.nextLine();
            nioSocketChannel.write(str);
        }

        TimeUnit.DAYS.sleep(1);
    }
}
